package com.example.hu.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by hasee on 2016-08-23.
 */
public class ImageUtil {

    public static String takePhoto(String path, byte[] frame, int width, int height) {
        try {
            File dir = new File(path);
            if (!dir.exists())
                dir.mkdirs();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            YuvImage yuvimage = new YuvImage(frame, ImageFormat.NV21, width, height, null);
            yuvimage.compressToJpeg(new Rect(0, 0, width, height), 100, bos);
            byte[] photo = bos.toByteArray();
            String filePath = path + "IMG_" + System.currentTimeMillis() + ".jpg";
            saveBitmapFile(BitmapFactory.decodeByteArray(photo,0,photo.length),new File(filePath));
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void saveBitmapFile(Bitmap bitmap, File file) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            fileOutputStream.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
